// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();

const db = cloud.database();
const col = db.collection('post_scan');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  // 查询数据
  let user = await col.where({
    '_openid': wxContext.OPENID,
  }).get();
  user = user.data[0];

  // if (user.prize !== null){
  //   return {
  //     msg: '你已经抽奖了!!!',
  //     success: false,
  //   }
  // }

  let rand = Math.random();
  let prize;
  switch(true){
    case(rand < 0.1):
      prize = 1;
      break;
    case (rand >= 0.1 && rand < 0.4):
      prize = 2;
      break;
    case (rand >= 0.4):
      prize = 0;
      break;
  }

  // 选中的邮卡数量 -1
  let zero = event.selectedArr[0];
  let one = event.selectedArr[1];
  user.words[zero].number -= 1;
  user.words[one].number -= 1;

  await col.where({
    '_openid': wxContext.OPENID,
  }).update({
    data:{
      prize: prize,
      words: user.words
    }
  });

  return {  // 返回给前端的数据 
    prize: prize, 
    success: true,
    myCards: user.words  
  }
}